package com.grupobbva.iici.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class Conexion {

	static Logger logger = Logger.getLogger(Conexion.class.getName());
	
	public static Connection getConnection() throws Exception {
		InitialContext context = null;
		DataSource dataSource = null;		
		Connection con = null;
		try {
			context = new InitialContext();
			
			dataSource = (DataSource) context.lookup("jdbc/IICI");
			con = dataSource.getConnection();
		} catch (Exception e) {
			try {
				dataSource = (DataSource) context.lookup("java:/comp/env/jdbc/IICI");
				con = dataSource.getConnection();
			} catch (Exception e2) {
				// e2.printStackTrace();
				throw e2;
			}
		}
		
		return con;
	}

	public static void close(Connection cnn, Statement stm, ResultSet ... rst) {
		try {
			if (rst != null) {
				for(ResultSet rs: rst){
					if(rs!=null){
						rs.close();		
					}
				}
			}
			if (stm != null) {
				stm.close();
			}
			if (cnn != null) {
				cnn.close();
			}
		} catch (SQLException e) {
			// e.printStackTrace();
			logger.error(e);
		}
	}
	
	public static void commit(Connection cnn) {
		try {
			if(cnn!=null){cnn.commit();}
		} catch (SQLException e) {
			// e.printStackTrace();
			logger.error(e);
		}
	}
	public static void rollback(Connection cnn) {
		try {
			if(cnn!=null){cnn.rollback();}
		} catch (SQLException e) {
			// e.printStackTrace();
			logger.error(e);
		}
	}
}
